package com.aaa.controller;

import com.aaa.vo.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.aaa.entity.Dept;
import com.aaa.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 部门表(Dept)表控制层
 *
 * @author makejava
 * @since 2022-12-07 10:11:16
 */
@RestController
@RequestMapping("dept")
public class DeptController {
    /**
     * 服务对象
     */
    @Resource
    private DeptService deptService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 分页查询所有数据
     *
     * @param page 分页对象
     * @param dept 查询实体
     * @return 所有数据
     */
    @GetMapping
    public Result selectAll(Page<Dept> page, Dept dept) {
        return Result.success(this.deptService.page(page, new QueryWrapper<>(dept)));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public Result selectOne(@PathVariable Serializable id) {
        ValueOperations<String, Object> forValue = redisTemplate.opsForValue();

        //1. 查询缓存: key的名称： 【模块名称::类名::唯一主键】
        Dept dept = (Dept) forValue.get("dept::" + id);
        if(dept != null){
            return Result.success(dept);
        }
        Dept byId = this.deptService.getById(id);
        forValue.set("dept::"+id,byId,3600, TimeUnit.SECONDS);
        return Result.success(byId);
    }

    /**
     * 新增数据
     *
     * @param dept 实体对象
     * @return 新增结果
     */
    @PostMapping
    public Result insert(@RequestBody Dept dept) {
        return Result.success(this.deptService.save(dept));
    }

    /**
     * 修改数据
     *
     * @param dept 实体对象
     * @return 修改结果
     */
    @PutMapping
    public Result update(@RequestBody Dept dept) {
        boolean b = this.deptService.updateById(dept);
        if(b){
            ValueOperations<String, Object> forValue = redisTemplate.opsForValue();
            forValue.set("dept::"+dept.getId(),dept,3600,TimeUnit.SECONDS);
        }
        return Result.success(b);
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @DeleteMapping
    public Result delete(@RequestParam("idList") List<Long> idList) {
        // 删除缓存中指定的key
        idList.stream().map(i -> {
            redisTemplate.delete("dept::" + i);
            return i;
        }).collect(Collectors.toList());
        //只删除了数据库
        return Result.success(this.deptService.removeByIds(idList));
    }
}

